package com.wzh.yebServe.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.swing.text.AbstractDocument;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author wzh
 * @create 2022/11/9 12:39
 * @Description: 此处注意swagger2与springboot的版本不兼容
 */
@EnableSwagger2
@Configuration
public class SwaggerConfig {
    @Bean
 public Docket createRestApi(){
     return new Docket(DocumentationType.SWAGGER_2)
             .apiInfo(apiInfo())
             .select()
             .apis(RequestHandlerSelectors.basePackage("com.wzh.yebServe.controller"))
             .paths(PathSelectors.any())
             .build()
             .securityContexts(securityContext())
             .securitySchemes(securitySchemes());
 }

 private ApiInfo apiInfo(){
     Contact contact=new Contact("wzh","http:localhost:8081/doc.html","2638885696@qq.com");
     return new ApiInfo(
             " 湖南文理学院办公系统", // 标题
             "基于web的湖南文理学院办公系统", // 描述
             "v1.0", // 版本
             "A301工作室提供", // 组织链接
             contact, // 联系人信息
             "Apach 2.0 许可", // 许可
             "许可链接", // 许可连接
             new ArrayList<> ()// 扩展
     );

 }
// 为swagger添加授权
    private List<ApiKey> securitySchemes(){
        //设置请求头信息
        List<ApiKey> result= new ArrayList<>();
        ApiKey apiKey = new ApiKey("Authorization","Authorization","Header");
        result.add(apiKey);
        return result;
    }

    public List<SecurityContext> securityContext(){
        //设置需要登录的路径
        List<SecurityContext> result = new ArrayList<>();
        result.add (getContextByPath("/hello/.*"));
        return  result;
    }


    private SecurityContext getContextByPath(String pathRegex) {

        return SecurityContext.builder ()
                .securityReferences (defultAuth())
                .forPaths (PathSelectors.regex (pathRegex))
                .build ();
    }

    private List<SecurityReference> defultAuth() {

        List<SecurityReference> result = new ArrayList<>();
        //授权范围                                                      //全局                    //描述
        AuthorizationScope authorizationScope = new AuthorizationScope("global","accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        result.add(new SecurityReference("Authorization",authorizationScopes));
        return result;
    }
}
